package com.ztsoft.user.utils;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.ztsoft.user.pojo.entity.project.ChooseConstruction;
import com.ztsoft.user.pojo.entity.project.Construction;
import com.ztsoft.user.pojo.vo.project.ConstructionVo;
import com.ztsoft.user.service.project.ChooseConstructionService;
import com.ztsoft.user.service.project.ConstructionService;

import java.util.ArrayList;
import java.util.List;

public class ConstructionListener extends AnalysisEventListener<ConstructionVo> {
    private final ConstructionService constructionService;
    private final ChooseConstructionService chooseConstructionService;
    private final String chooseId;

    public ConstructionListener(ConstructionService constructionService, ChooseConstructionService chooseConstructionService, String chooseId) {
        this.constructionService = constructionService;
        this.chooseConstructionService = chooseConstructionService;
        this.chooseId = chooseId;
    }

    private static final int BATCH_COUNT = 10;
    List<Construction> list = new ArrayList<>();

    @Override
    public void invoke(ConstructionVo constructionVo, AnalysisContext analysisContext) {
        Construction construction = new Construction();
        BeanUtil.copyProperties(constructionVo, construction);
        list.add(construction);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData(); // 调用下面的持久化方法
            // 存储完成清理 list
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
    }

    private void saveData() {
        // 保存班组人员信息
        constructionService.saveBatch(list);
        // 保存物资与班组人员关联关系
        list.forEach(construction -> chooseConstructionService.save(new ChooseConstruction(chooseId, construction.getId())));
    }

}